<?php

namespace app\common\util;

use Closure;
use InvalidArgumentException;

/**
 * 一个简易的闭包管理器
 */
class ClosureManager
{
    /**
     * @var array<string, Closure>
     */
    private $closures = [];

    /**
     * 添加闭包函数到指定分组
     *
     * @param string $group 分组名称
     * @param Closure $closure 闭包函数
     */
    public function addClosure(string $group, Closure $closure)
    {
        $this->closures[$group][] = $closure;
    }

    /**
     * 为指定分组的所有闭包设置参数
     *
     * @param string $group 分组名称
     * @param array $parameters 参数数组
     * @throws InvalidArgumentException 如果分组不存在
     */
    public function setParameters(string $group, array $parameters)
    {
        if (isset($this->closures[$group])) {
            foreach ($this->closures[$group] as $key => $closure) {
                // 使用新的闭包，将参数传递给原始闭包
                $this->closures[$group][$key] = fn() => $closure(...$parameters);
            }
        } else {
            throw new InvalidArgumentException("Group '$group' does not exist.");
        }
    }

    /**
     * 应用所有闭包函数并返回执行结果数组
     *
     * @return array 执行结果数组
     */
    public function apply()
    {
        $results = [];
        foreach ($this->closures as $groupClosures) {
            foreach ($groupClosures as $closure) {
                // 执行闭包并将结果存储在数组中
                $results[] = $closure();
            }
        }
        return $results;
    }
}
